package web

import (
	"encoding/json"
	"go-zookeeper-demo/app/zookeeper"
)

type Server struct {
}

//GetTask 获取节点任务信息
func (s *Server) GetTask() ([]map[string]interface{}, error) {
	////ConnectForHttp 返回一个可用的zookeeper链接，http web使用
	conn := zookeeper.ConnectForHttp()

	taskInfo, _, err := conn.Get(zookeeper.GetTaskPath())

	if err != nil {
		return nil, err
	}

	taskMap := make([]map[string]interface{}, 100)
	// Unmarshal解码信息成Json，并存储到 v interface{}中
	// taskInfo格式为[]byte
	json.Unmarshal(taskInfo, &taskMap)

	return taskMap, err
}

func (s *Server) UpdateTask(data string) error {
	// 获得链接
	conn := zookeeper.ConnectForHttp()
	// 更新信息
	_, err := conn.Set(zookeeper.GetTaskPath(), []byte(data), -1)

	return err
}

//GetNodes 获取集群所有节点
func (s *Server) GetNodes() ([]string, error) {
	conn := zookeeper.ConnectForHttp()

	children, _, err := conn.Children(zookeeper.GetNodesPath())

	return children, err
}

//GetNode 获取节点信息
func (s *Server) GetNode(nodeName string) (map[string]string, error) {
	conn := zookeeper.ConnectForHttp()

	nodeInfo, _, err := conn.Get(zookeeper.GetNodePath() + nodeName)
	if err != nil {
		return nil, err
	}

	childrenMap := make(map[string]string)
	json.Unmarshal(nodeInfo, &childrenMap)

	return childrenMap, err
}

//GetNodeTask 获取节点任务信息
func (s *Server) GetNodeTask() (map[string]map[string]int, error) {
	conn := zookeeper.ConnectForHttp()

	nodeTaskInfo, _, err := conn.Get(zookeeper.GetNodeTaskPath())

	if err != nil {
		return nil, err
	}

	nodeTaskMap := make(map[string]map[string]int)
	json.Unmarshal(nodeTaskInfo, &nodeTaskMap)

	return nodeTaskMap, err
}
